<script lang="ts" setup>
import {ref, reactive, toRefs, onMounted, onBeforeMount} from "vue";
import CatalogService from "../stores/CatalogService"
import { ElMessage, ElMessageBox } from "element-plus";
import routes from "../routes";
import { log } from "console";

let isLogin = ref(false)
const categories = ref([
  {
    categoryId: '',
    name: '',
    description: ''
  }
])
const products = ref([])

let loginAccount = reactive({
  username: '',
  listOption: ''
})
const toProduct = ( (categoryId)=>{
  routes.push({
    name:'product',
    params: {
      categoryId:categoryId
    }
  })
})
//检查是否登录
const checkIsLogin = () =>{
  let data = window.sessionStorage.getItem('loginAccount')
  if(data != null){
    // console.log(data)
    // console.log(JSON.parse(data))
    loginAccount = JSON.parse(data)
    isLogin.value = true
    // console.log(loginAccount.username)
  }else{
    isLogin.value = false
  }
}
//获取categries
const getCategories = async () => {
  const [err, res] = await CatalogService.promise_process(CatalogService.getCategories())
  if(err){
    console.log(err)
    ElMessage({
      message: '请求服务器失败',
      type: 'error',
    })
  }
  if(res){
    //  console.log(res)
    categories.value = res.data
    // console.log(categories.value)
  }
}
const logout = () => {
  window.sessionStorage.removeItem('loginAccount')
  checkIsLogin()
  ElMessageBox.alert('成功退出', '提示', {
    type: 'success',
    confirmButtonText: 'OK',
    callback: () => {
      routes.push('/home')
    },
  })
}
const state = reactive({
  logoUrl:'/static/img/logo.jpg'
})

const {logoUrl} = toRefs(state)

interface shopItem{
  value: string
  productId: string
  categoryId: string
}

const search = ref('')
const items = ref<shopItem[]>([])
const querySearch = (querystring: string,cb: any)=>{
  const results = querystring
      ? items.value.filter(createFilter(querystring))
      : items.value
  cb(results)
}
const createFilter = (querystring: string)=>{
  return (item: shopItem) => {
    return (
        item.value.toLowerCase().indexOf(querystring.toLowerCase()) === 0
    )
  }
}

// todo
const loadAll = async () => {
  const [err, res] = await CatalogService.promise_process(CatalogService.getAllProducts());
  if(res){
    //console.log(res.data)

    products.value = res.data
    // console.log(products.value)
  }
  let searchItems = [{value:'',productId:'',categoryId:''}]
  products.value.forEach(el => {
    searchItems.push({
      value: el.name,
      productId: el.productId,
      categoryId: el.categoryId
    })
  });
  items.value = searchItems

}

const handleSelect = (item: shopItem) => {
  console.log(item)
  toItem(item.categoryId, item.productId)
}

const toItem =  (cid,pid)=>{
  routes.push({
    name:"item",
    params: {
      categoryId:cid ,
      productId :pid
    }
  })
}

onBeforeMount(() => {
  loadAll()
  checkIsLogin()
  getCategories()
})

</script>

<template>
    <el-header class="header">
        <el-row :gutter="20" class="el-row">
            <el-col :span="8">
                <router-link to="/home">
                    <div class="logo"><el-avatar shape="square" :size="70" :src="logoUrl"/></div>
                </router-link>
            </el-col>
            <el-col :span="8">
                <el-breadcrumb separator="|" class="el-row">
                    <el-breadcrumb-item :to="{ path: '/cart'}"><el-icon color="white" :size="30"><ShoppingCart /></el-icon></el-breadcrumb-item>

                    <el-breadcrumb-item :to="{ path: '/account/edit'}"><el-text class="mx-1" type="warning"> My Account</el-text></el-breadcrumb-item>
<!--&lt;!&ndash;                    已登录&ndash;&gt;-->
                    <el-breadcrumb-item v-if="isLogin" @click="logout"><el-text class="mx-1" type="warning"> Logout</el-text></el-breadcrumb-item>
<!--&lt;!&ndash;                    未登录&ndash;&gt;-->
                       <el-breadcrumb-item v-else :to="{ path: '/login'}"><el-text class="mx-1" type="warning"> Login</el-text></el-breadcrumb-item>
                    <el-breadcrumb-item :to="{path:'/'}"><el-icon><QuestionFilled /></el-icon></el-breadcrumb-item>

                </el-breadcrumb>
            </el-col>
            <el-col :span="8">
                <div class="mt-4">
                    <div class="el-autocomplete">
                    <el-autocomplete
                        v-model="search"
                        :fetch-suggestions="querySearch"
                        :trigger-on-focus="false"
                        clearable
                        class="inline-input w-50"
                        placeholder="请输入所查找的商品"
                        @select="handleSelect"
                    />
                </div>
                    <el-button @click="null"><el-icon :size="22"><Search /></el-icon></el-button>
                </div>
            </el-col>
        </el-row>

        <!-- 方便开发 ，快速页面跳转-->

        <!-- <nav>
        <router-link to="/login">登录 |</router-link>
        <router-link to="/register">注册 |</router-link>
        <router-link to="/account/edit">修改个人信息 |</router-link>
        <router-link to="/cart">购物车|</router-link>
        <router-link to="/catalog/category">Category|</router-link>
        <router-link to="/order">订单 |</router-link>
        <router-link to="/order/add">添加订单 |</router-link>
        <router-link to="/order/confirm">确认订单</router-link>
        </nav> -->
        <nav>
            <span v-for="category in categories" style="color: deepskyblue" @click="toProduct(category.categoryId)">
                {{ category.name }} |
            </span>


        </nav>

  </el-header>

</template>

<style scoped>
.header{
  height: 70px;
  color: #fff;
  background-color: #0c0821;
  top: 0;
  width: 100vw;
  position: fixed;
  left: 0;
  z-index: 10;
}

.el-row{
  height: 70px;
}

.el-autocomplete{
  margin: 20px 10px;
}

.logo{
  position: fixed;
  top: 0;
  left: 0;
}

.scrollbar-flex-content {
  display: flex;
}
.scrollbar-demo-item {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100px;
  height: 50px;
  margin: 10px;
  text-align: center;
  border-radius: 4px;
  background: var(--el-color-danger-light-9);
  color: var(--el-color-danger);
}

</style>
